import requests
import sys
import os

from common import AuthInfo, BaseMachineInfo, OSDeploy


def get_arg(key):
    for arg in sys.argv[1:]:
        if arg.startswith(f"{key}="):
            return arg.split("=", 1)[1]
    return None


def clone_config(maas_url, api_key, src_host, target_hosts, clone_type):
    clone_type = clone_type.lower()
    interfaces_flag = False
    storage_flag = False

    if clone_type == "interface":
        interfaces_flag = True
    elif clone_type == "disk":
        storage_flag = True
    elif clone_type == "both":
        interfaces_flag = True
        storage_flag = True
    else:
        raise ValueError(f"未知 clone_type: {clone_type}, 可选值: interface, disk, both")
    auth = AuthInfo(maas_url, api_key)
    src_info = BaseMachineInfo(auth.session, maas_url, src_host)
    src_id = src_info.results[0].get("system_id")
    target_hosts = BaseMachineInfo(auth.session, maas_url, target_hosts)
    target_ids = [i.get("system_id") for i in target_hosts.results]
    clone_type = clone_type.lower()
    interfaces_flag = False
    storage_flag = False

    clone_url = f"{maas_url}/2.0/machines/op-clone"
    payload = {
        "source": src_id,
        "destinations": target_ids,
        "interfaces": interfaces_flag,  # 根据 type 决定
        "storage": storage_flag  # 根据 type 决定
    }

    # 使用 multipart/form-data 发送 POST 请求
    response = auth.session.post(clone_url, files=payload)

    if response.status_code == 204:
        print("克隆操作成功，配置已应用到目标机器")
    else:
        print(f"克隆失败: {response.status_code} {response.text}")


if __name__ == '__main__':
    maas_url = os.getenv("maas_url")
    api_key = os.getenv("api_key")

    src_host = get_arg("src_host")
    target_hosts = get_arg("target_hosts")
    clone_type = get_arg("clone_type")
    clone_config(maas_url, api_key, src_host, target_hosts, clone_type, )
